package com.servlet;

import com.dao.imp.AddUpdDelDaoImp;
import com.dao.imp.FindCollectStatus;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/25 17:33
 **/

@WebServlet(name = "AddToFavoritesServlet", value = "/AddToFavoritesServlet")
public class AddToFavoritesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int good_id = Integer.parseInt(request.getParameter("id"));
        HttpSession session = request.getSession();
        Object userId = session.getAttribute("userId");
        int user_id = Integer.parseInt(userId.toString());

        String countSql = "SELECT 1 FROM user_collect WHERE good_id="+good_id+" LIMIT 1";
        int result = FindCollectStatus.isInit(countSql);

        if (result==0){
            String insertSql = "INSERT INTO onlineshop.user_collect (user_id, good_id, status) VALUES ("+user_id+", "+good_id+", 1)";
            AddUpdDelDaoImp addUpdDelDaoImp = new AddUpdDelDaoImp();
            addUpdDelDaoImp.addUpdDelGoods(insertSql);
        }else {
            String updateSql = " UPDATE user_collect  SET status = 1 WHERE user_id = "+user_id+" AND good_id="+good_id;
            AddUpdDelDaoImp addUpdDelDaoImp = new AddUpdDelDaoImp();
            addUpdDelDaoImp.addUpdDelGoods(updateSql);
        }



//        JSONObject json = JSONObject.fromObject("{data:\"success\"}");
//
//        response.getWriter().print(json);
    }
}
